<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportEmployees">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="employeesList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" sortable="" width="200">
            <template v-slot:default="{row}">
              <img v-imgerr="require('@/assets/common/head.jpg')" :src="row.staffPhoto" alt="" class="avatarImg" @click="AvatrDialog(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatterEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="{row}">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="AssignRoleFn(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="!checkPerm('POINT-USER-UPDATE')" @click="delEmployeesBtn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="page.total"
            :page-size="page.size"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <AddEmployess :show-dialog.sync="showDialog" @updataFn="getEmployeesList" />
      <el-dialog :visible.sync="showAvatrDialog" title="图片">
        <el-row type="flex" justify="center">
          <canvas ref="canvasImg" />
        </el-row>
      </el-dialog>
      <AssignRole ref="assignrole" :user-id="userId" :show-dialog.sync="showAssign" />
    </div>
  </div>
</template>

<script>
import QRcode from 'qrcode'
import AddEmployess from './components/add-employess.vue'
import EmployeeEnum from '@/api/constant/employees'
import { delEmployees, getEmployeesList } from '@/api/employees'
import { formatDate } from '@/filters/index.js'
import AssignRole from './components/assign-role.vue'
export default {
  components: {
    AddEmployess,
    AssignRole
  },
  data() {
    return {
      employeesList: [],
      page: {
        page: 1,
        size: 5,
        total: 0
      },
      loading: false,
      showDialog: false,
      departmentsList: [],
      showAvatrDialog: false,
      showAssign: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeesList()
  },
  methods: {
    // 角色管理
    async  AssignRoleFn(id) {
      await this.$refs.assignrole.getUserDetail(id)
      this.showAssign = true
      this.userId = id
    },
    // 点击图片
    AvatrDialog(imgUrl) {
      this.showAvatrDialog = true
      this.$nextTick(() => {
        if (imgUrl) {
          QRcode.toCanvas(this.$refs.canvasImg, imgUrl, {
            width: 140,
            color: {
              dark: '#34a5f1'
            }
          })
        }
      })
    },
    // 获取员工列表
    async getEmployeesList() {
      this.loading = true
      const { rows, total } = await getEmployeesList(this.page)
      // staffPhoto
      // console.log(rows)
      this.employeesList = rows
      this.page.total = total
      this.loading = false
    },
    // 当分页页面改变时触发
    currentChange(index) {
      this.page.page = index
      this.getEmployeesList()
    },
    //  格式化招聘形式
    formatterEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '试用期'
    },
    // 导出
    async exportEmployees() {
      const { rows } = await getEmployeesList({
        page: 1,
        size: this.page.total
      })
      // console.log(rows)
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const header = Object.keys(dict)
      const newData = rows.map(user => {
        return this.en2zh(user, dict)
      })
      // console.log(import('@/vendor/Export2Excel'))
      const obj = await import('@/vendor/Export2Excel')
      obj.export_json_to_excel({
        header,
        data: newData
      })
    },
    // 数据转换
    en2zh(user, dict) {
      // console.log(formatDate)
      const arr = []
      // 接收每个用户和字典
      Object.keys(dict).forEach(key => {
        const newKey = dict[key]
        let value = user[newKey]
        if (newKey === 'formOfEmployment') {
          const obj = EmployeeEnum.hireType.find(item => item.id === user[newKey])
          value = obj ? obj.value : '临时工'
        }
        if (newKey === 'timeOfEntry' || newKey === 'correctionTime') {
          value = formatDate(value)
        }
        arr.push(value)
      })
      // 遍历每个用户
      // header和data 数据转换
      return arr
    },
    // 删除员工
    async  delEmployeesBtn(id) {
      try {
      //  二次提醒
        await this.$confirm('是否删除？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 发送请求
        await delEmployees(id)
        // 提示用户
        this.$message.success('删除成功')
        // 更新数据
        if (this.employeesList.length === 1 && this.page.page > 1) {
          this.page.page--
        }
        this.getEmployeesList()
      } catch (error) {
        console.log(error)
      }
    }

  }
}
</script>

<style lang='scss' scoped>
.avatarImg{
   width: 200px;
   height: 130px;
   object-fit: contain;
}
</style>
